﻿using System.Data;

namespace SX.Data
{
	public partial class DbContext
	{
		private DbCommand CreateCommand(bool isReadOnly = false)
		{
			 
				IDbConnection connection = null;

				if (Data.UseTransaction
				    || Data.UseSharedConnection)
				{
					if (Data.Connection == null)
					{
						Data.Connection = (IDbConnection) Data.AdoNetProvider.CreateConnection();
						Data.Connection.ConnectionString = ConnectionStringHelper.GetWriteConnectionString(Data.ConnectionString) ;
					}
					connection = Data.Connection;
				}
				else
				{
					connection = (IDbConnection)Data.AdoNetProvider.CreateConnection();
				    string conn = Data.ConnectionString;

				    if (isReadOnly)
				    {
				        conn = ConnectionStringHelper.GetReadConnectionString(Data.ConnectionString);
				    }
				    else
				    {
				        conn = ConnectionStringHelper.GetWriteConnectionString(Data.ConnectionString);
				    }
                    connection.ConnectionString = conn;
				}
			 
				var cmd = connection.CreateCommand();
				cmd.Connection = connection;

				return new DbCommand(this, cmd);
			 
		}
        public IDbCommand Sql(string sql,bool isReadOnly, params object[] parameters)
        {
            var command = CreateCommand(isReadOnly).Sql(sql).Parameters(parameters);
            return command;
        }
        public IDbCommand Sql(string sql, params object[] parameters)
		{
			var command = CreateCommand().Sql(sql).Parameters(parameters);
			return command;
		}

		public IDbCommand MultiResultSql
		{
            get
	        {
	            var command = CreateCommand().UseMultiResult(true);
	            return command;
	        }
	    }
	}
}
